package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/*
* 团油接口 -无查询
* */
@Slf4j
public class Plugin_ECARD_P020 implements ChannelService {

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            String AccountVal = String.valueOf(data.get("AccountVal"));
            if (Pattern.matches("^1[3456789]\\d{9}$", AccountVal) != true) {
                return  ChannelResult.error("手机号码异常");
            }
            long timestampInSeconds = System.currentTimeMillis();

            HashMap<String, String> params = new HashMap<>();
            params.put("app_key",apiConfig.getString("appKey"));
            params.put("timestamp",String.valueOf(timestampInSeconds));
            params.put("platformType",apiConfig.getString("platformType"));
            params.put("orderNo",String.valueOf(data.get("ChannelOrderCode")));
            params.put("userPhone",AccountVal);
            params.put("productId",String.valueOf(data.get("SUPProductId")));

            String key = apiConfig.getString("secretKey");
            String submitUrl = apiConfig.getString("SubmitUrl");

            String sign = encryptParameters(params, key);
            params.put("sign",sign);

            //String res = sendPost(submitUrl, params);
            String res = HttpTool.HttpPost(submitUrl, params);
            JSONObject reqParams = JSONObject.parseObject(res);
            Integer code = reqParams.getInteger("code");
            String message = reqParams.getString("message");

            if(code.equals(200)){
                return ChannelResult.success("充值成功");
            }
            return ChannelResult.FAILED("充值失败##"+message);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("团油提交订单接口错误：",e);
            return  ChannelResult.error("团油提交订单接口错误");
        }
    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Query");
        return  ChannelResult.success("success");
    }


    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }



    public static String encryptParameters(Map<String, String> parameters,String secretKey) throws NoSuchAlgorithmException {
        StringBuilder sb = new StringBuilder();
        // 按照字母顺序排序参数
        parameters.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(entry -> sb.append(entry.getKey()).append(entry.getValue()));

        // 添加秘钥
        sb.insert(0, secretKey).append(secretKey);

        System.out.println(sb);
        // 使用MD5进行32位小写加密
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(sb.toString().getBytes());
        byte[] digest = md.digest();
        StringBuilder hexString = new StringBuilder();
        for (byte b : digest) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String sendPost(String url, Map<String,String> param) {
        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(param),"utf-8"));
            log.info("httpPost请求："+url+"?"+JSONObject.toJSONString(param));
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result= EntityUtils.toString(responseEntity);
                log.info("httpPost请求返回："+JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }



}
